import { defineStore } from "pinia";
import { ref } from "vue";

export const useWebSocketStore = defineStore("useWebSocketStore", () => {
  const webSocket = ref();
  const timeout = 30 * 1000; // 30秒一次心跳
  const timeoutObj = ref(); //心跳倒计时
  const serverTimeoutObj = ref(); //心跳倒计时
  const timeoutNum = ref(); //断开 重连倒计时
  const lockReconnect = ref(false); //重连锁
  const userId = ref();
  //联系人Id
  const contactId = ref<number>(0);

  function setContactId(id: number) {
    contactId.value = id;
  }

  function initWebSocket(id: number) {
    if (!id) return;
    userId.value = id;
    webSocket.value = new WebSocket(`${process.env.VUE_APP_WS_URL}${id}`);
    webSocket.value.onopen = () => onopen();
    webSocket.value.onclose = () => onclose();
    webSocket.value.onerror = (e: any) => onerror(e);
    webSocket.value.onmessage = (e: any) => onmessage(e);
  }

  //开始心跳
  function start() {
    console.log("start");
    //清除延时器
    timeoutObj.value && clearTimeout(timeoutObj.value);
    serverTimeoutObj.value && clearTimeout(serverTimeoutObj.value);
    timeoutObj.value = setTimeout(() => {
      if (webSocket.value && webSocket.value.readyState == 1) {
        webSocket.value.send("heartBath"); //发送消息，服务端返回信息，即表示连接良好，可以在socket的onmessage事件重置心跳机制函数
      } else {
        reconnect();
      }
      //定义一个延时器等待服务器响应，若超时，则关闭连接，重新请求server建立socket连接
      serverTimeoutObj.value = setTimeout(() => {
        webSocket.value.close();
      }, timeout);
    }, timeout);
  }

  function reset() {
    // 重置心跳
    // 清除时间
    clearTimeout(timeoutObj.value);
    clearTimeout(serverTimeoutObj.value);
    // 重启心跳
    start();
  }

  // 重新连接
  function reconnect() {
    if (lockReconnect.value) return;
    lockReconnect.value = true;
    //没连接上会一直重连，设置延迟避免请求过多
    timeoutNum.value && clearTimeout(timeoutNum.value);
    timeoutNum.value = setTimeout(() => {
      initWebSocket(userId.value);
      lockReconnect.value = false;
    }, 5000);
  }

  const onopen = () => {
    //开启心跳
    start();
    console.log(
      "WebSocket连接成功!!!" + new Date() + "----" + webSocket.value.readyState
    );
  };

  function onerror(e: any) {
    console.log("WebSocket连接发生错误" + e);
  }

  function onclose() {
    webSocket.value.close();
    clearTimeout(timeoutObj.value);
    clearTimeout(serverTimeoutObj.value);
    console.log("WebSocket连接关闭");
    reconnect();
  }

  async function onmessage(event: any) {
    reset();
    // 自定义全局监听事件
    window.dispatchEvent(
      new CustomEvent("onmessageWS", {
        detail: {
          data: event.data,
        },
      })
    );
  }

  function send(message: string) {
    webSocket.value.send(message);
  }

  function closeWebSocket() {
    // 关闭websocket
    if (webSocket.value) {
      webSocket.value.close();
    }
  }

  return {
    send,
    closeWebSocket,
    initWebSocket,
    setContactId,
    contactId,
  };
});
